﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace Clover.BaseAuth
{
    public class PermissionValidtor
    {
        public static bool Validate(ActionDescriptor actionDescriptor)
        {
            var validResult = ValidPermission(actionDescriptor);

            if (validResult == ValidResult.NoExist)
            {
                validResult = ValidPermission(actionDescriptor.ControllerDescriptor);
            }

            return validResult == ValidResult.True;
        }

        public static bool GetPermissionAttribute(ICustomAttributeProvider customAttributeProvider, out IPermissionAttribute permissionAttribute)
        {
            permissionAttribute = (customAttributeProvider.GetCustomAttributes(typeof(IPermissionAttribute), false) as IPermissionAttribute[])?.FirstOrDefault();
            return permissionAttribute != null;
        }

        public static ValidResult ValidPermission(IPermissionAttribute permission)
        {
            return PermissionCacheSerializer.GetPermissions().Intersect(permission.Permissions).Any()
                    ? ValidResult.True : ValidResult.False;
        }

        public static ValidResult ValidPermission(ICustomAttributeProvider customAttributeProvider)
        {
            if (GetPermissionAttribute(customAttributeProvider, out IPermissionAttribute permission))
            {
                return ValidPermission(permission);
            }
            else
            {
                return ValidResult.NoExist;
            }
        }


        public enum ValidResult
        {
            NoExist,
            True,
            False
        }
    }
}
